package calificaciones;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import sistemas.sam.R;
import tutorias.conexion.Bean;

import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class Datos_Calificacion extends Activity implements OnItemSelectedListener,OnClickListener {

	
	JSONArray jArray=null;
	String result = null;
	String matricula,materia_nom;
	InputStream is = null;
	StringBuilder sb = null;
	String grupo2="";
	String dirr;
	String []materias;
	String []materias_id;
	String []grupo;
	String []grupoID;
	String index,idU;
	int idM;
	Button verLista;
	
	String php,variable,valor,valor2,campo;
	private ConectarSam mAuthTask = null;
	ArrayAdapter<String> adaptado2;
	ArrayAdapter<String> adaptado3;
	ArrayAdapter<String> adaptado4;
	public List<String> Lmateria =new ArrayList<String>(); 
	public List<String> Lmate =new ArrayList<String>(); 
	public List<String> Lmateria2 =new ArrayList<String>(); 
	public List<String> LgrupoID =new ArrayList<String>(); 
	public List<String> Lunidades =new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_datos__calificacion);
		
		
		Bean bean=new Bean();
		dirr=bean.getDireccion();
		php="MateriaProfesor";
		valor="20110TI001";
		
		variable="id";
		campo="materiaP";
		Bundle extra=getIntent().getExtras();
		grupo=extra.getStringArray("grupo");
		grupoID=extra.getStringArray("grupoID");
		
		for(int i=0;i<grupoID.length;i++){
			LgrupoID.add(""+grupoID[i]);
		}
		
		
		for(int i=0;i<grupo.length;i++){	
			Lmateria.add(""+grupo[i]);
		}
		
		unidades uni=new unidades();
		Lunidades.addAll(uni.unidad());
		
		
		adaptado2 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, Lmateria);
		Spinner sp = (Spinner) findViewById(R.id.grupo);
		adaptado2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp.setAdapter(adaptado2);
		
		
		adaptado3 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, Lmate);
		Spinner sp2 = (Spinner) findViewById(R.id.materia);
		adaptado3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp2.setAdapter(adaptado3);
		
		adaptado4 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, Lunidades);
		Spinner sp3 = (Spinner) findViewById(R.id.unidad);
		adaptado4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp3.setAdapter(adaptado4);
		
		
		
		sp.setOnItemSelectedListener(this);
		sp2.setOnItemSelectedListener(this);
		sp3.setOnItemSelectedListener(this);
		
		adaptado3.notifyDataSetChanged();
				
		
		verLista=(Button) findViewById(R.id.listaAlum);
		verLista.setOnClickListener(this);
				
	}
	
	
	
	public void llenar(String [] grupo,String [] m){
		Lmate.clear();
		Lmateria2.clear();
		
		for(int i=0;i<grupo.length;i++){
			Lmate.add(""+grupo[i]);
		}
		
		
		for(int i=0;i<m.length;i++){
			Lmateria2.add(""+m[i]);
		}
		adaptado3.notifyDataSetChanged();
	}

	private void abrirDashboard() {
	//	selectAsesoria.putExtra("materias", materias);
		//startActivity(selectAsesoria);
		llenar(materias_id,materias);
		
	}
	public class ConectarSam extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			// http post
			
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(dirr+php+
						".php?"+variable+"="+valor+"&grupo_id="+index);
				Log.v("log_tag", dirr+php+
						".php?"+variable+"="+valor+"&grupo_id="+index);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
			} catch (Exception e) {
				Log.e("log_tag", " "
						+ e.toString());
			}
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");

				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				result = sb.toString();
				Log.v(" obtenido", result);
			} catch (Exception e) {
				Log.e("log_tag",
						"Error convirtiendo datos recibidos" + e.toString());
			}
			try {
				jArray = new JSONArray(result);
				JSONObject json_data = null;
				materias =new String[jArray.length()]; 
				materias_id=new String[jArray.length()];
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					materias[i]= json_data.getString(campo);	
				materias_id[i]=json_data.getString("nombre");	
					Log.d("msg", "paso  "+materias[i]);
					Log.d("mate_id", "paso  "+materias_id[i]);
				}
			} catch (JSONException e1) {
				Log.e("JSON ERR", e1.getMessage());
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
			return true;
		}
		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			//showProgress(false);
			Log.v("login_resultado", success.toString());
			if (success) {
				
				abrirDashboard();

			} else {
				
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			//showProgress(false);
		}
	}
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int location,
			long arg3) {
		
			
		if(arg0.getId()==R.id.grupo){
			
			index=""+LgrupoID.get(location);
			//Toast.makeText(getApplicationContext(), ""+index, Toast.LENGTH_LONG).show();
			
			adaptado3.notifyDataSetChanged();
			
			mAuthTask=new ConectarSam();
			mAuthTask.execute((Void)null);
			
		}
		if(arg0.getId()==R.id.unidad){
			idU=""+(location+1);
				
		}
		
if(arg0.getId()==R.id.materia){
	
			idM=location;
			
		}
		
	}



	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}



	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	String idm=	""+Lmateria2.get(0);
		
		Intent i=new Intent (this,AlumnosAltaCalif.class);
		Bundle bundle = new Bundle();
		
		bundle.putString("idG",index);
		bundle.putString("idU",idU);
		bundle.putString("idM",idm);
		i.putExtras(bundle);
		startActivity(i);
		
	}

}


